﻿using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Engine;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NP.BPMReportPlatform.RecurringJobs
{
    /// <summary>
    /// 引擎Job
    /// </summary>
    public class EngineJob : BpmReportPlatformRecurringJob, IEngineJob
    {
        private readonly SqlSugarClient _dbEngine;

        /// <summary>
        /// 构造函数
        /// </summary>
        public EngineJob(ISqlSugarAppService sqlSugarAppService)
        {
            _dbEngine = sqlSugarAppService.GetEngineInstance();
        }

        ///// <summary>
        ///// 归档记录表
        ///// </summary>
        ///// <returns></returns>
        //public async Task ArchiveRecordsTable()
        //{
        //    var startDate = DateTime.Now.AddMonths(-3).AddDays(-7);
        //    var endDate = DateTime.Now.AddMonths(-3);

        //    var instanceNumberList = await _dbEngine.Queryable<Instances, InstanceStates>((i, ins) => new JoinQueryInfos(JoinType.Inner, i.InstanceId == ins.InstanceId))
        //        .With(SqlWith.NoLock).Where((i, ins) => ins.Status == 2 && SqlFunc.Between(ins.LatestArriveTime, startDate, endDate)).Select(i => i.Number).Distinct().ToListAsync();

        //    if (instanceNumberList.Count > 0)
        //    {
        //        var cnt = instanceNumberList.Count / 30;
        //        if (instanceNumberList.Count % 30 > 0)
        //        {
        //            cnt++;
        //        }

        //        for (var k = 0; k < cnt; k++)
        //        {
        //            var instanceNumberArray = instanceNumberList.Skip(k * 30).Take(30).ToArray();
        //            var recordsList = await _dbEngine.Queryable<Records, ActivityComments>((r, a) => new JoinQueryInfos(JoinType.Inner, r.RecordId == a.RecordId)).
        //                With(SqlWith.NoLock).Where((r, a) => instanceNumberArray.Contains(r.InstanceNumber) && a.Content.Equals("同意")).ToListAsync();
        //            if (recordsList.Count == 0)
        //            {
        //                continue;
        //            }

        //            try
        //            {
        //                _dbEngine.Ado.BeginTran();

        //                var recordsHistoryList = ObjectMapper.Map<List<Records>, List<RecordsHistory>>(recordsList);
        //                await _dbEngine.Insertable(recordsHistoryList).ExecuteCommandAsync();

        //                await _dbEngine.Deleteable<Records>(recordsList).ExecuteCommandAsync();


        //                _dbEngine.Ado.CommitTran();
        //            }
        //            catch (Exception ex)
        //            {
        //                _dbEngine.Ado.RollbackTran();
        //            }

        //        }
        //    }

        //}
    }
}
